﻿using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using MVVMComun;
using System.Collections.Generic;
using System.Linq;
using System;


namespace UpdateWeatherTask
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private string Pais;
        private string Ciudad;
        private MVVMComun.CityWeatherModel model;
        private List<Pronostico> pronosticos; 

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            LoadSettings();
            updateModel();
           
        }



        private void LoadSettings()
        {
            System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("Pais"))
            {
                Pais = settings["Pais"].ToString();

            }
            else
            {

                Pais = "Venezuela";
            }
            if (settings.Contains("Ciudad"))
            {
                Ciudad = settings["Ciudad"].ToString();

            }
            else
            {
                Ciudad = "Barquisimeto";
            }

        }

        private void updateModel()
        {
            model = new MVVMComun.CityWeatherModel();
            model.Ciudad = Ciudad;
            model.Pais = Pais;

            model.WeatherResponseReady += (s, e) => {
                pronosticos = e.Result;
                updateTile();
                NotifyComplete();
            };
            model.getForeCast();
        }

        


        private void updateTile()
        {
            var tile = Microsoft.Phone.Shell.ShellTile.ActiveTiles.First();
            var cdata = new Microsoft.Phone.Shell.FlipTileData();
            cdata.Count = int.Parse(pronosticos[0].TempC);
            cdata.BackContent = pronosticos[0].TempC + " C° " + pronosticos[0].TempF + " F°" + Environment.NewLine + Environment.NewLine + pronosticos[0].Condicion + Environment.NewLine + DateTime.Now.ToShortDateString();
            cdata.BackTitle = "Clima: " + Ciudad;
            tile.Update(cdata);
        }


    }
}